//
//  QSMyInfoViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/19.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSMyInfoViewController.h"
#import "QSMyInfoCell.h"
#import <TZImagePickerController.h>
#import "QSOSSUploadHelper.h"
#import "QSUserInterface.h"
@interface QSMyInfoViewController ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIButton *logoutButton;
@property (nonatomic, strong)NSMutableArray *assetsArray;
@property (nonatomic, strong)NSMutableArray *photoArray;
@property (nonatomic, strong)QSUserModel *currentUser;
@end
static NSString *myInfoUserIconCell = @"MyInfoUserIconCell";
static NSString *myInfoDefaultCell = @"MyInfoDefaultCell";

@implementation QSMyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _currentUser = [QSUserManager sharedQSUserManager].user;
    [self configSubView];
    
}

- (void)configSubView{
    self.navigationItem.title = @"个人中心";
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
//    [self.view addSubview:self.logoutButton];
    [self.view addSubview:self.tableView];
    
//    [_logoutButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.view).offset(kRealValue(26));
//        make.right.equalTo(self.view).offset(- kRealValue(26));
//        make.bottom.equalTo(self.view).offset(- kRealValue(57));
//        make.height.offset(kRealValue(44));
//    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.top.height.equalTo(self.view);
//        make.bottom.equalTo(_logoutButton.mas_top).offset(- kRealValue(30));
    }];
}

#pragma mark -- 懒加载
- (UIButton *)logoutButton{
    if (!_logoutButton) {
        _logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [_logoutButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
        _logoutButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
        _logoutButton.titleLabel.font = [UIFont QSFontOfSize16];
        _logoutButton.layer.cornerRadius = 22;
        [_logoutButton addTarget:self action:@selector(logOutAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _logoutButton;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
        _tableView.layer.cornerRadius = 5;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"QSMyInfoCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:myInfoUserIconCell];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:myInfoDefaultCell];
    }
    return _tableView;
}

- (NSMutableArray *)assetsArray{
    if (!_assetsArray) {
        _assetsArray = [NSMutableArray array];
    }
    return _assetsArray;
}

- (NSMutableArray *)photoArray{
    if (!_photoArray) {
        _photoArray = [NSMutableArray array];
    }
    return _photoArray;
}
#pragma mark -- TableViewDelegate & TableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return kRealValue(70);
    }else{
        return kRealValue(49);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        
        QSMyInfoCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:myInfoUserIconCell];
        }
        if (kCurrentUser.headPic && kCurrentUser.headPic.length > 1) {
            [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:kCurrentUser.headPic]];
        }else{
            [cell.userImageView setImage:[UIImage imageNamed:@"user_defult_icon"]];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }else{
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:myInfoDefaultCell];
        if (indexPath.row == 1) {
            cell.textLabel.text = @"姓名";
            cell.detailTextLabel.text = _currentUser.name;
        }else if (indexPath.row == 2){
            cell.textLabel.text = @"手机号";
            cell.detailTextLabel.text = _currentUser.phone;
        }else{
            cell.textLabel.text = @"角色";
            cell.detailTextLabel.text = _currentUser.roleName;
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        
        // 是否显示可选原图按钮
        imagePicker.allowPickingOriginalPhoto = NO;
        // 是否允许显示视频
        imagePicker.allowPickingVideo = NO;
        // 是否允许显示图片
        imagePicker.allowPickingImage = YES;
        
        // 这是一个navigation 只能present
        // 设置 模态弹出模式。 iOS 13默认非全屏
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

// 选择照片的回调
-(void)imagePickerController:(TZImagePickerController *)picker
      didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                sourceAssets:(NSArray *)assets
       isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [QSOSSUploadHelper asyncUploadFilesToOSS:photos complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
        if (!error) {
            NSString *imageUrl = names.lastObject;
            DLog(@"%@", imageUrl);
            [QSAppKeyWindow showIndeterminateHudWithText:@"正在更改"];
            [self changeUserImageWithImageUrl:imageUrl];
        }else{
            [QSAppKeyWindow showAutoHideHudWithText:@"上传失败"];
        }
    }];
}

- (void)changeUserImageWithImageUrl:(NSString *)imageUrl{
    [QSUserInterface changeUserImageWithImageUrl:imageUrl AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            [QSAppKeyWindow showAutoHideHudWithText:@"更改成功"];
            kCurrentUser.headPic = imageUrl;
            [[QSUserManager sharedQSUserManager] saveUser:kCurrentUser];
            [self.tableView reloadData];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_USERIMAGEFINISH" object:nil];
        }else{
            [QSAppKeyWindow showAutoHideHudWithText:@"上传失败"];
        }
    }];
}

- (void)logOutAction:(UIButton *)sender{
    [QSUserInterface logoutWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            NSLog(@"退出成功");
        }
    }];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kLoginStateKey];
    [[QSUserManager sharedQSUserManager] removeUser];    
    [[QSUserManager sharedQSUserManager] turnToLoginViewController];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
